package org.ust.extraction;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Vector;

public class Finder
{
	public void extract ( File uncompressedDir )
	{
		// TODO: Debug!!
		int c = 0 , Lmt = 1;

		Vector < File > jarFiles = findJarFiles ( uncompressedDir );

		for ( File jarFile : jarFiles )
		{
			if ( c >= Lmt )
			{
				break;
			}
			System.out.println ( jarFile.getName ( ) );
			Uncompressor uncompressor = null;

			try
			{
				uncompressor = new Uncompressor ( jarFile );
			}
			catch ( FileNotFoundException e )
			{
				e.printStackTrace ( );
			}
			catch ( NotZipFileException e )
			{
				e.printStackTrace ( );
			}
			catch ( IOException e )
			{
				e.printStackTrace ( );
			}

			if ( uncompressor == null )
			{
				break;
			}

			int dotIdx = jarFile.getAbsolutePath ( ).lastIndexOf ( "." );
			String jarFilePath = jarFile.getAbsolutePath ( ).substring ( 0 ,
					dotIdx );
			File jarFileFolder = new File ( jarFilePath );
			Vector < File > classFiles = findClassFiles ( jarFileFolder );
			for ( File classFile : classFiles )
			{
				if ( c++ >= Lmt )
				{
					break;
				}
				System.out
						.println ( "Class Anaylsing: " + classFile.getName ( ) );
				try
				{
					new Analyzer ( classFile );
				}
				catch ( IOException e )
				{
					e.printStackTrace ( );
				}
			}
		}
	}

	public Vector < File > findZipFiles ( File rootDirStr )
	{
		File [ ] listFiles = rootDirStr.listFiles ( );
		Vector < File > files = new Vector < File > ( listFiles.length );
		for ( File file : listFiles )
		{
			if ( isSpecifiedFile ( file , "zip" ) )
			{
				files.add ( file );
			}
		}
		return files;
	}

	public Vector < File > findClassFiles ( File rootDirStr )
	{
		File [ ] listFiles = rootDirStr.listFiles ( );
		Vector < File > files = new Vector < File > ( listFiles.length );
		for ( File file : listFiles )
		{
			if ( isSpecifiedFile ( file , "class" ) )
			{
				files.add ( file );
			}
		}
		return files;
	}

	public Vector < File > findJarFiles ( File rootDirStr )
	{
		File [ ] listFiles = rootDirStr.listFiles ( );
		Vector < File > files = new Vector < File > ( listFiles.length );
		for ( File file : listFiles )
		{
			if ( isSpecifiedFile ( file , "jar" ) )
			{
				files.add ( file );
			}
		}
		return files;
	}

	private boolean isSpecifiedFile ( File file , String ext )
	{
		String name = file.getName ( );
		int lastIndexOfDot = name.lastIndexOf ( "." );
		String t = name.substring ( lastIndexOfDot + 1 );
		return t.equals ( ext );
	}
}
